package Base;

import javax.swing.*;
import java.awt.*;

public class DScrollPane extends JPanel {
    private int speed = (-60);                // 滚动速度
    public JPanel panel = new JPanel();     // 内部容器
    public static int heightIntercept = 10; // 高度间隔
    private int height = 0;

    public DScrollPane() {
        super();
        setLayout(null);
        setOpaque(false);
        panel.setLayout(null);
        panel.setOpaque(false);
        add(panel);

        // 测试
//        setBounds(0, 0, 200, 200);
//        setBackground(Color.blue);
//        panel.setBounds(0, 0, 100, 600);
//        panel.setBackground(Color.white);

        // 滚动监听
        addMouseWheelListener(e -> {
            if (height < getHeight())
                return;

            int y = e.getWheelRotation() * speed;
            panel.setLocation(panel.getX(), panel.getY() + y);
            if (e.getWheelRotation() > 0 && panel.getY() + panel.getHeight() < getHeight()) {
                panel.setLocation(0, getHeight() - height);
            }
            if (e.getWheelRotation() < 0 && panel.getY() > 0) {
                panel.setLocation(0, 0);
            }

//            System.out.print("y=" + panel.getY() + "\n");
            repaint();
        });
    }

    public void addComp(Component comp) {
        comp.setLocation(comp.getX(), height);
        panel.setSize(getWidth(), Math.max(panel.getHeight(), getHeight()));
        panel.add(comp);
        height += comp.getHeight() + heightIntercept;
        if (height > panel.getHeight()) {
            panel.setSize(getWidth(), height);
            panel.setLocation(panel.getX(), getHeight()-height);
        }

        repaint();
        if (getParent() != null)
            getParent().repaint();
    }

}
